<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="isEdit ? '编辑用户' : '新增用户'"
    width="600px"
    :before-close="handleClose"
    @update:model-value="dialogVisible = $event"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="formData.username"
          placeholder="请输入用户名"
          :disabled="isEdit"
        />
      </el-form-item>
      
      <el-form-item v-if="!isEdit" label="密码" prop="password">
        <el-input
          v-model="formData.password"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>
      
      <el-form-item label="真实姓名" prop="realName">
        <el-input
          v-model="formData.realName"
          placeholder="请输入真实姓名"
        />
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="formData.email"
          placeholder="请输入邮箱"
        />
      </el-form-item>
      
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="formData.phone"
          placeholder="请输入手机号"
        />
      </el-form-item>
      
      <el-form-item label="头像" prop="avatar">
        <el-input
          v-model="formData.avatar"
          placeholder="请输入头像URL"
        />
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="角色" prop="roleIds">
        <el-select
          v-model="formData.roleIds"
          multiple
          placeholder="请选择角色"
          style="width: 100%"
        >
          <el-option
            v-for="role in roleOptions"
            :key="role.id"
            :label="role.roleName"
            :value="role.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useUserStore } from '@/stores/user'
import type { User, UserCreateDTO, UserUpdateDTO, Role } from '@/api/user'

interface Props {
  visible: boolean
  userData?: User | null
  isEdit: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const userStore = useUserStore()

// 表单引用
const formRef = ref<FormInstance>()
const loading = ref(false)

// 角色选项
const roleOptions = ref<Role[]>([
  { id: 1, roleName: '超级管理员', roleCode: 'SUPER_ADMIN', description: '系统超级管理员', status: 1 }
])

// 表单数据
const formData = reactive<UserCreateDTO & UserUpdateDTO>({
  username: '',
  password: '',
  realName: '',
  email: '',
  phone: '',
  avatar: '',
  status: 1,
  roleIds: []
})

// 表单验证规则
const formRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    {
      validator: async (rule, value, callback) => {
        if (value && !props.isEdit) {
          try {
            const exists = await userStore.checkUsername(value)
            if (exists) {
              callback(new Error('用户名已存在'))
            } else {
              callback()
            }
          } catch (error) {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '真实姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
    {
      validator: async (rule, value, callback) => {
        if (value) {
          try {
            const exists = await userStore.checkEmail(value)
            if (exists && value !== props.userData?.email) {
              callback(new Error('邮箱已存在'))
            } else {
              callback()
            }
          } catch (error) {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
    {
      validator: async (rule, value, callback) => {
        if (value) {
          try {
            const exists = await userStore.checkPhone(value)
            if (exists && value !== props.userData?.phone) {
              callback(new Error('手机号已存在'))
            } else {
              callback()
            }
          } catch (error) {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    username: '',
    password: '',
    realName: '',
    email: '',
    phone: '',
    avatar: '',
    status: 1,
    roleIds: []
  })
  formRef.value?.clearValidate()
}

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 监听用户数据变化
watch(
  () => props.userData,
  (newData) => {
    if (newData) {
      Object.assign(formData, {
        username: newData.username,
        realName: newData.realName,
        email: newData.email,
        phone: newData.phone,
        avatar: newData.avatar || '',
        status: newData.status,
        roleIds: newData.roles?.map(role => role.id) || []
      })
    } else {
      resetForm()
    }
  },
  { immediate: true }
)

// 监听对话框显示状态
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      if (!props.userData) {
        resetForm()
      }
    }
  }
)

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    if (props.isEdit && props.userData) {
      // 编辑用户
      const updateData: UserUpdateDTO = {
        realName: formData.realName,
        email: formData.email,
        phone: formData.phone,
        avatar: formData.avatar,
        status: formData.status,
        roleIds: formData.roleIds
      }
      await userStore.updateUser(props.userData.id, updateData)
      ElMessage.success('用户更新成功')
    } else {
      // 新增用户
      const createData: UserCreateDTO = {
        username: formData.username,
        password: formData.password,
        realName: formData.realName,
        email: formData.email,
        phone: formData.phone,
        avatar: formData.avatar,
        status: formData.status,
        roleIds: formData.roleIds
      }
      await userStore.createUser(createData)
      ElMessage.success('用户创建成功')
    }
    
    emit('success')
  } catch (error) {
    console.error('表单提交失败:', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
.dialog-footer {
  text-align: right;
}
</style>
